package com.laoguo.aop;

import com.laoguo.anno.DataSource;
import com.laoguo.config.CustomerContextHolder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
@ConditionalOnProperty(prefix = "guojunjie",name = "muti-datasource-open",havingValue = "true")
public class DataSourceAop implements Ordered {

    private Logger log = LoggerFactory.getLogger(DataSourceAop.class);

    @Pointcut(value = "execution( * com.laoguo.service.*.*(..))")
    private void cut() {
    }


    @Around("cut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        Signature signature = point.getSignature();
        MethodSignature methodSignature = null;
        if(! (signature instanceof MethodSignature)){
            throw new IllegalArgumentException("该注解只能用于方法");
        }
        methodSignature = (MethodSignature) signature;

        Object target = point.getTarget();
        Method currentMethod = target.getClass().getMethod(methodSignature.getName(),methodSignature.getParameterTypes());
        DataSource datasource = currentMethod.getAnnotation(DataSource.class);
        if (datasource != null) {
            CustomerContextHolder.setCustomerType(datasource.name());
            log.debug("设置数据源为：" + datasource.name());
        } else {
            CustomerContextHolder.setCustomerType(CustomerContextHolder.DATA_SOURCE_MASTER);
            log.debug("设置数据源为：dataSourceCore");
        }
        try {
            return point.proceed();
        } finally {
            log.debug("清空数据源信息！");
            CustomerContextHolder.clearCustomerType();
        }

    }




    @Override
    public int getOrder() {
        return 1;
    }
}
